# AI Agent Platform 开发环境设置脚本 (Windows)
# 作者: Claude
# 日期: 2025-01-19

param(
    [string]$DatabaseType = "SqlServer",
    [string]$ProjectPath = ".",
    [switch]$SkipDatabase,
    [switch]$SkipDocker,
    [switch]$Force
)

# 设置控制台编码为 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 颜色输出函数
function Write-ColorOutput($ForegroundColor) {
    $fc = $host.UI.RawUI.ForegroundColor
    $host.UI.RawUI.ForegroundColor = $ForegroundColor
    if ($args) {
        Write-Output $args
    }
    $host.UI.RawUI.ForegroundColor = $fc
}

# 检查命令是否存在
function Test-Command($Command) {
    return [bool](Get-Command -Name $Command -ErrorAction SilentlyContinue)
}

# 检查 .NET SDK
function Test-DotNetSDK {
    Write-ColorOutput Cyan "检查 .NET SDK..."

    if (Test-Command "dotnet") {
        $dotnetVersion = dotnet --version
        Write-ColorOutput Green "✓ .NET SDK 已安装: $dotnetVersion"

        $majorVersion = $dotnetVersion.Split('.')[0]
        if ($majorVersion -lt 8) {
            Write-ColorOutput Red "✗ 需要 .NET 8.0 或更高版本，当前版本: $dotnetVersion"
            return $false
        }
        return $true
    } else {
        Write-ColorOutput Red "✗ .NET SDK 未安装"
        Write-ColorOutput Yellow "请从 https://dotnet.microsoft.com/download 下载 .NET 8.0 SDK"
        return $false
    }
}

# 检查 Node.js (可选)
function Test-NodeJS {
    Write-ColorOutput Cyan "检查 Node.js..."

    if (Test-Command "node") {
        $nodeVersion = node --version
        Write-ColorOutput Green "✓ Node.js 已安装: $nodeVersion"
        return $true
    } else {
        Write-ColorOutput Yellow "⚠ Node.js 未安装 (可选，用于前端开发)"
        return $false
    }
}

# 检查 Git
function Test-Git {
    Write-ColorOutput Cyan "检查 Git..."

    if (Test-Command "git") {
        $gitVersion = git --version
        Write-ColorOutput Green "✓ Git 已安装: $gitVersion"
        return $true
    } else {
        Write-ColorOutput Red "✗ Git 未安装"
        Write-ColorOutput Yellow "请从 https://git-scm.com/download 下载 Git"
        return $false
    }
}

# 检查 Docker (可选)
function Test-Docker {
    if ($SkipDocker) {
        Write-ColorOutput Yellow "⚠ 跳过 Docker 检查"
        return $true
    }

    Write-ColorOutput Cyan "检查 Docker..."

    if (Test-Command "docker") {
        $dockerVersion = docker --version
        Write-ColorOutput Green "✓ Docker 已安装: $dockerVersion"
        return $true
    } else {
        Write-ColorOutput Yellow "⚠ Docker 未安装 (可选，用于容器化)"
        return $false
    }
}

# 设置数据库
function Setup-Database {
    if ($SkipDatabase) {
        Write-ColorOutput Yellow "⚠ 跳过数据库设置"
        return $true
    }

    Write-ColorOutput Cyan "设置数据库..."

    switch ($DatabaseType) {
        "SqlServer" {
            return Setup-SqlServer
        }
        "PostgreSQL" {
            return Setup-PostgreSQL
        }
        "MySQL" {
            return Setup-MySQL
        }
        default {
            Write-ColorOutput Red "✗ 不支持的数据库类型: $DatabaseType"
            return $false
        }
    }
}

# 设置 SQL Server
function Setup-SqlServer {
    Write-ColorOutput Cyan "检查 SQL Server..."

    # 检查 SQL Server 服务
    $sqlServices = Get-Service -Name "MSSQL*" -ErrorAction SilentlyContinue
    if ($sqlServices) {
        Write-ColorOutput Green "✓ 找到 SQL Server 服务:"
        foreach ($service in $sqlServices) {
            Write-ColorOutput Green "  - $($service.Name) ($($service.Status))"
        }

        # 检查 SQL Server 端口
        $tcpPort = 1433
        $portInfo = netstat -ano | findstr ":$tcpPort"
        if ($portInfo) {
            Write-ColorOutput Green "✓ SQL Server 端口 $tcpPort 正在监听"
        } else {
            Write-ColorOutput Yellow "⚠ SQL Server 端口 $tcpPort 未找到"
        }

        return $true
    } else {
        Write-ColorOutput Yellow "⚠ 未找到 SQL Server 服务"

        if (-not $SkipDocker -and (Test-Command "docker")) {
            Write-ColorOutput Cyan "尝试启动 SQL Server Docker 容器..."
            try {
                docker run -d --name sql_server_demo `
                    -e "ACCEPT_EULA=Y" `
                    -e "MSSQL_SA_PASSWORD=yourStrong(!)Password" `
                    -p 1433:1433 `
                    mcr.microsoft.com/mssql/server:2022-latest

                if ($LASTEXITCODE -eq 0) {
                    Write-ColorOutput Green "✓ SQL Server Docker 容器已启动"
                    Write-ColorOutput Yellow "请等待 1-2 分钟让容器完全启动"
                    return $true
                } else {
                    Write-ColorOutput Red "✗ 启动 SQL Server Docker 容器失败"
                    return $false
                }
            } catch {
                Write-ColorOutput Red "✗ 启动 SQL Server Docker 容器失败: $_"
                return $false
            }
        } else {
            Write-ColorOutput Yellow "请手动安装 SQL Server 或使用 Docker"
            return $false
        }
    }
}

# 设置 PostgreSQL
function Setup-PostgreSQL {
    Write-ColorOutput Cyan "检查 PostgreSQL..."

    if (Test-Command "psql") {
        Write-ColorOutput Green "✓ PostgreSQL 客户端已安装"
        return $true
    } else {
        Write-ColorOutput Yellow "⚠ PostgreSQL 客户端未安装"

        if (-not $SkipDocker -and (Test-Command "docker")) {
            Write-ColorOutput Cyan "尝试启动 PostgreSQL Docker 容器..."
            try {
                docker run -d --name postgres `
                    -e POSTGRES_PASSWORD=yourpassword `
                    -p 5432:5432 `
                    postgres:13

                if ($LASTEXITCODE -eq 0) {
                    Write-ColorOutput Green "✓ PostgreSQL Docker 容器已启动"
                    return $true
                } else {
                    Write-ColorOutput Red "✗ 启动 PostgreSQL Docker 容器失败"
                    return $false
                }
            } catch {
                Write-ColorOutput Red "✗ 启动 PostgreSQL Docker 容器失败: $_"
                return $false
            }
        } else {
            Write-ColorOutput Yellow "请手动安装 PostgreSQL 或使用 Docker"
            return $false
        }
    }
}

# 设置 MySQL
function Setup-MySQL {
    Write-ColorOutput Cyan "检查 MySQL..."

    if (Test-Command "mysql") {
        Write-ColorOutput Green "✓ MySQL 客户端已安装"
        return $true
    } else {
        Write-ColorOutput Yellow "⚠ MySQL 客户端未安装"

        if (-not $SkipDocker -and (Test-Command "docker")) {
            Write-ColorOutput Cyan "尝试启动 MySQL Docker 容器..."
            try {
                docker run -d --name mysql `
                    -e MYSQL_ROOT_PASSWORD=yourpassword `
                    -p 3306:3306 `
                    mysql:8.0

                if ($LASTEXITCODE -eq 0) {
                    Write-ColorOutput Green "✓ MySQL Docker 容器已启动"
                    return $true
                } else {
                    Write-ColorOutput Red "✗ 启动 MySQL Docker 容器失败"
                    return $false
                }
            } catch {
                Write-ColorOutput Red "✗ 启动 MySQL Docker 容器失败: $_"
                return $false
            }
        } else {
            Write-ColorOutput Yellow "请手动安装 MySQL 或使用 Docker"
            return $false
        }
    }
}

# 检查端口占用
function Test-PortUsage {
    Write-ColorOutput Cyan "检查端口占用..."

    $ports = @(5000, 44300, 5432, 3306, 1433, 6379)

    foreach ($port in $ports) {
        $portInfo = netstat -ano | findstr ":$port"
        if ($portInfo) {
            Write-ColorOutput Yellow "⚠ 端口 $port 已被占用"
            $portInfo
        } else {
            Write-ColorOutput Green "✓ 端口 $port 可用"
        }
    }
}

# 设置项目
function Setup-Project {
    Write-ColorOutput Cyan "设置项目..."

    # 检查项目路径
    if (-not (Test-Path $ProjectPath)) {
        Write-ColorOutput Red "✗ 项目路径不存在: $ProjectPath"
        return $false
    }

    # 进入项目目录
    Set-Location $ProjectPath

    # 检查解决方案文件
    $slnFiles = Get-ChildItem -Filter "*.sln" -Recurse | Select-Object -First 1
    if (-not $slnFiles) {
        Write-ColorOutput Red "✗ 未找到解决方案文件"
        return $false
    }

    Write-ColorOutput Green "✓ 找到解决方案文件: $($slnFiles.Name)"

    # 恢复 NuGet 包
    Write-ColorOutput Cyan "恢复 NuGet 包..."
    dotnet restore

    if ($LASTEXITCODE -eq 0) {
        Write-ColorOutput Green "✓ NuGet 包恢复成功"
    } else {
        Write-ColorOutput Red "✗ NuGet 包恢复失败"
        return $false
    }

    # 编译项目
    Write-ColorOutput Cyan "编译项目..."
    dotnet build --configuration Debug

    if ($LASTEXITCODE -eq 0) {
        Write-ColorOutput Green "✓ 项目编译成功"
    } else {
        Write-ColorOutput Red "✗ 项目编译失败"
        return $false
    }

    return $true
}

# 创建配置文件
function Create-ConfigFile {
    Write-ColorOutput Cyan "创建配置文件..."

    $apiProjectPath = Get-ChildItem -Filter "*HttpApi.Host.csproj" -Recurse | Select-Object -First 1
    if (-not $apiProjectPath) {
        Write-ColorOutput Red "✗ 未找到 API 项目"
        return $false
    }

    $apiProjectDir = $apiProjectPath.DirectoryName
    $configPath = Join-Path $apiProjectDir "appsettings.Development.json"

    if ((Test-Path $configPath) -and -not $Force) {
        Write-ColorOutput Yellow "⚠ 配置文件已存在: $configPath"
        Write-ColorOutput Yellow "使用 -Force 参数覆盖现有配置"
        return $true
    }

    # 创建配置文件内容
    $configContent = @"
{
  "ConnectionStrings": {
    "Default": "$($GetConnectionString())",
    "Redis": "localhost:6379"
  },
  "App": {
    "ServerRootAddress": "https://localhost:44300/",
    "ClientRootAddress": "http://localhost:4200/",
    "CorsOrigins": "http://localhost:4200,http://localhost:8080,http://localhost:3001"
  },
  "AuthServer": {
    "Authority": "https://localhost:44300/",
    "RequireHttpsMetadata": "false",
    "SwaggerClientId": "AgentPlatform_Swagger",
    "SwaggerClientSecret": "1q2w3e*"
  },
  "AI": {
    "ModelProviders": {
      "OpenAI": {
        "ApiKey": "your-openai-api-key",
        "BaseUrl": "https://api.openai.com/v1/"
      },
      "ZhipuAI": {
        "ApiKey": "your-zhipuai-api-key",
        "BaseUrl": "https://open.bigmodel.cn/api/paas/v4/"
      }
    }
  },
  "EnhancedModelService": {
    "EnableEnhancedFeatures": true,
    "MonitoringConfig": {
      "Enabled": true,
      "EnableDetailedLogging": true
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "CKY.AgentPlatform": "Debug",
      "Microsoft": "Warning",
      "Microsoft.EntityFrameworkCore": "Information"
    }
  }
}
"@

    $configContent | Out-File -FilePath $configPath -Encoding UTF8
    Write-ColorOutput Green "✓ 配置文件已创建: $configPath"

    return $true
}

# 获取连接字符串
function Get-ConnectionString {
    switch ($DatabaseType) {
        "SqlServer" {
            return "Server=localhost;Database=AgentPlatform;User Id=sa;Password=yourStrong(!)Password;TrustServerCertificate=true;"
        }
        "PostgreSQL" {
            return "Host=localhost;Database=AgentPlatform;Username=postgres;Password=yourpassword;"
        }
        "MySQL" {
            return "Server=localhost;Database=AgentPlatform;User=root;Password=yourpassword;"
        }
        default {
            return "Server=localhost;Database=AgentPlatform;Trusted_Connection=True;TrustServerCertificate=true;"
        }
    }
}

# 运行数据库迁移
function Run-DatabaseMigration {
    if ($SkipDatabase) {
        Write-ColorOutput Yellow "⚠ 跳过数据库迁移"
        return $true
    }

    Write-ColorOutput Cyan "运行数据库迁移..."

    $migratorProjectPath = Get-ChildItem -Filter "*DbMigrator.csproj" -Recurse | Select-Object -First 1
    if (-not $migratorProjectPath) {
        Write-ColorOutput Red "✗ 未找到数据库迁移项目"
        return $false
    }

    $migratorProjectDir = $migratorProjectPath.DirectoryName
    Set-Location $migratorProjectDir

    try {
        dotnet run --environment Development

        if ($LASTEXITCODE -eq 0) {
            Write-ColorOutput Green "✓ 数据库迁移成功"
            return $true
        } else {
            Write-ColorOutput Red "✗ 数据库迁移失败"
            return $false
        }
    } catch {
        Write-ColorOutput Red "✗ 运行数据库迁移时出错: $_"
        return $false
    }
}

# 显示后续步骤
function Show-NextSteps {
    Write-ColorOutput Cyan "`n🎯 设置完成！后续步骤："
    Write-ColorOutput Yellow "1. 编辑配置文件中的 API Key:"
    Write-ColorOutput Yellow "   - 打开 appsettings.Development.json"
    Write-ColorOutput Yellow "   - 替换 'your-openai-api-key' 为真实的 OpenAI API Key"
    Write-ColorOutput Yellow "   - 替换 'your-zhipuai-api-key' 为真实的智谱AI API Key"

    Write-ColorOutput Yellow "`n2. 启动应用:"
    Write-ColorOutput Yellow "   - 在 Visual Studio 中打开解决方案"
    Write-ColorOutput Yellow "   - 设置 CKY.AgentPlatform.HttpApi.Host 为启动项目"
    Write-ColorOutput Yellow "   - 按 F5 启动调试"

    Write-ColorOutput Yellow "`n3. 验证应用:"
    Write-ColorOutput Yellow "   - 访问 https://localhost:44300/swagger/"
    Write-ColorOutput Yellow "   - 访问 https://localhost:44300/health"

    Write-ColorOutput Yellow "`n4. 调试提示:"
    Write-ColorOutput Yellow "   - 使用 F10/F11 进行单步调试"
    Write-ColorOutput Yellow "   - 查看输出窗口中的日志"
    Write-ColorOutput Yellow "   - 检查 Swagger UI 进行 API 测试"
}

# 主函数
function Main {
    Write-ColorOutput Magenta "`n🚀 AI Agent Platform 开发环境设置脚本"
    Write-ColorOutput Magenta "=========================================`n"

    # 检查必要组件
    $dotnetOk = Test-DotNetSDK
    $gitOk = Test-Git
    $nodeOk = Test-NodeJS
    $dockerOk = Test-Docker

    Write-ColorOutput Cyan "`n检查端口占用..."
    Test-PortUsage

    if (-not ($dotnetOk -and $gitOk)) {
        Write-ColorOutput Red "`n❌ 必要组件检查失败，请先安装缺失的组件"
        exit 1
    }

    # 设置数据库
    $databaseOk = Setup-Database

    # 设置项目
    $projectOk = Setup-Project

    if (-not $projectOk) {
        Write-ColorOutput Red "`n❌ 项目设置失败"
        exit 1
    }

    # 创建配置文件
    $configOk = Create-ConfigFile

    # 运行数据库迁移
    if ($databaseOk) {
        $migrationOk = Run-DatabaseMigration
    } else {
        Write-ColorOutput Yellow "⚠ 跳过数据库迁移"
        $migrationOk = $true
    }

    # 总结
    Write-ColorOutput Cyan "`n📊 设置结果："
    Write-ColorOutput Green "✓ .NET SDK: $($dotnetOk ? "正常" : "异常")"
    Write-ColorOutput Green "✓ Git: $($gitOk ? "正常" : "异常")"
    Write-ColorOutput Green "✓ Node.js: $($nodeOk ? "正常" : "异常")"
    Write-ColorOutput Green "✓ Docker: $($dockerOk ? "正常" : "异常")"
    Write-ColorOutput Green "✓ 数据库: $($databaseOk ? "正常" : "异常")"
    Write-ColorOutput Green "✓ 项目: $($projectOk ? "正常" : "异常")"
    Write-ColorOutput Green "✓ 配置文件: $($configOk ? "正常" : "异常")"
    Write-ColorOutput Green "✓ 数据库迁移: $($migrationOk ? "正常" : "异常")"

    if ($projectOk -and $configOk) {
        Write-ColorOutput Green "`n✅ 开发环境设置成功！"
        Show-NextSteps
    } else {
        Write-ColorOutput Red "`n❌ 开发环境设置失败，请检查错误信息"
        exit 1
    }
}

# 执行主函数
Main